<template>
  <div ref="chartRef" :style="{ height, width }"></div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, Ref, watch } from 'vue';
  import { getCurrentWeightNumberUse, getCurrentWeightNumberUseByGoodsType } from '@/api/weight/weight';
  import { useECharts } from '@/hooks/web/useECharts';
  import { basicProps } from './props';

  interface WeightNumberUseItem {
    weightNumber: string;
    grossWeightNumber: number;
    tareWeightNumber: number;
  }

  export default defineComponent({
    props: {
      ...basicProps,
      selectedGoodsType: {
        type: Number,
        default: null
      }
    },
    setup(props) {
      const chartRef = ref<HTMLDivElement | null>(null);
      const weightNumberUseData = ref<WeightNumberUseItem[]>([]);
      const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

      const loadData = async () => {
        try {
          let res;
          if (props.selectedGoodsType) {
            // 如果有选中的商品类型，调用筛选API
            res = await getCurrentWeightNumberUseByGoodsType(props.selectedGoodsType);
          } else {
            // 否则调用默认API
            res = await getCurrentWeightNumberUse();
          }
          weightNumberUseData.value = res || [];
          // 更新图表数据
          updateChart();
        } catch (error) {
          console.error('获取数据失败:', error);
        }
      };

      const updateChart = () => {
        // 按weightNumber进行排序
        const sortedData = [...weightNumberUseData.value].sort((a, b) => {
          // 假设weightNumber是可比较的字符串
          return a.weightNumber.localeCompare(b.weightNumber);
        });

        if (sortedData.length === 0) {
          // 无数据时显示暂无数据
          setOptions({
            title: {
              text: '暂无数据',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#999',
                fontSize: 16
              }
            },
            xAxis: { show: false },
            yAxis: { show: false },
            series: []
          });
          return;
        }

        // 从排序后的数据中提取需要显示的数据
        const grossWeightData = sortedData.map(item => item.grossWeightNumber);
        const tareWeightData = sortedData.map(item => item.tareWeightNumber);
        const weightNumbers = sortedData.map(item => item.weightNumber);

        setOptions({
          legend: {
            data: ['毛重数量', '皮重数量'],
            top: 0
          },
          grid: {
            top: 30,
            bottom: 30,
            left: '3%',
            right: '4%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: weightNumbers
          },
          yAxis: {},
          series: [
              {
                name: '毛重数量',
                data: grossWeightData,
                type: 'bar',
                stack: 'x',
                label: {
                  show: true,
                  position: 'top',
                  formatter: '{c}'
                }
              },
              {
                name: '皮重数量',
                data: tareWeightData,
                type: 'bar',
                stack: 'x',
                label: {
                  show: true,
                  position: 'insideTop',
                  formatter: '{c}',
                  color: '#fff'
                }
              }
            ]
        });
      };

      // 监听selectedGoodsType的变化，当它变化时重新加载数据
      watch(() => props.selectedGoodsType, () => {
        loadData();
      });

      onMounted(() => {
        loadData();
      });
      return { chartRef };
    },
  });
</script>
